

# -*- coding: utf-8 -*-
"""
图片处理和发送示例
"""

import asyncio
import base64
import os
from PIL import Image
import io

# 导入playwright库
from playwright.async_api import async_playwright
import tempfile
from imgUtils import process_image
from sendUtils import send_data_async
from config import width,height
async def main():
    # 图片文件路径
    image_path = "1.bmp"
    
    # 检查文件是否存在
    if not os.path.exists(image_path):
        print(f"错误：找不到图片文件 {image_path}")
        return
    
    # 读取图片并获取尺寸
    with Image.open(image_path) as img:
        width, height = img.size
        print(f"图片尺寸: {width}x{height}")
        
        # 将图片转换为base64字符串
        buffered = io.BytesIO()
        img.save(buffered, format="BMP")
        img_base64 = base64.b64encode(buffered.getvalue()).decode("utf-8")
    
 

    try:
        print("步骤1: 处理图片...")
        img_base64 = process_image(img_base64)
 
        print("步骤2: 发送数据到设备...")
        result = await send_data_async(img_base64)
        
        if result:
            print("图片发送成功！")
        else:
            print("图片发送失败。")
    
    except Exception as e:
        print(f"处理过程中出错: {e}")

async def capture_and_send_webpage(url, classOrId=None):
    """
    从URL截取网页图片并发送到设备
    :param url: 网页URL
    :param classOrId: 要截取的元素的class或id选择器，如果为None则截取整个页面
    :return: 是否成功
    """
    try:
        # 导入必要的库
        from playwright.async_api import async_playwright
        import tempfile
        
        print(f"步骤1: 访问网页 {url}...")
        async with async_playwright() as p:
            # 启动浏览器
            browser = await p.chromium.launch()
            
            # 创建新页面并设置较大的视口大小以确保元素可见
            page = await browser.new_page(viewport={"width": 1920, "height": 1080})
            
            # 访问URL并等待网络空闲
            await page.goto(url, wait_until="networkidle")
            
            # 创建临时文件保存截图
            with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp_file:
                screenshot_path = tmp_file.name
            
            # 如果指定了元素选择器，则截取特定元素
            if classOrId:
                print(f"步骤1.1: 定位元素 {classOrId}...")
                # 确定是class还是id选择器
                selector = f"#{classOrId}" if not classOrId.startswith("#") and not classOrId.startswith(".") else classOrId
                
                try:
                    # 等待元素可见
                    element = await page.wait_for_selector(selector, state="visible", timeout=10000)
                    
                    if element:
                        # 截取元素图片
                        await element.screenshot(path=screenshot_path)
                        print(f"步骤1.2: 已截取元素 {classOrId} 的图片")
                    else:
                        print(f"警告: 未找到元素 {classOrId}，将截取整个页面")
                        await page.screenshot(path=screenshot_path, full_page=True)
                except Exception as e:
                    print(f"警告: 截取元素时出错: {e}，将截取整个页面")
                    await page.screenshot(path=screenshot_path, full_page=True)
            else:
                # 截取整个页面
                await page.screenshot(path=screenshot_path, full_page=True)
            
            # 关闭浏览器
            await browser.close()
        
        print(f"步骤2: 截图已保存到 {screenshot_path}")
        
        # 读取图片并进行等比例调整和补白处理
        with Image.open(screenshot_path) as img:
            orig_width, orig_height = img.size
            print(f"原始图片尺寸: {orig_width}x{orig_height}")
            
            # 计算等比例缩放后的尺寸
            ratio = min(width / orig_width, height / orig_height)
            new_width = int(orig_width * ratio)
            new_height = int(orig_height * ratio)
            
            # 调整图片大小，保持比例
            resized_img = img.resize((new_width, new_height), Image.LANCZOS)
            
            # 创建白色背景的新图片
            final_img = Image.new("RGB", (width, height), (255, 255, 255))
            
            # 计算居中位置
            paste_x = (width - new_width) // 2
            paste_y = (height - new_height) // 2
            
            # 将调整大小后的图片粘贴到白色背景上
            final_img.paste(resized_img, (paste_x, paste_y))
            
            # 将图片转换为base64字符串
            buffered = io.BytesIO()
            final_img.save(buffered, format="PNG")
            img_base64 = base64.b64encode(buffered.getvalue()).decode("utf-8")
        
        print("步骤3: 处理图片...")
        img_base64 = process_image(img_base64)
        
        print("步骤4: 发送数据到设备...")
        result = await send_data_async(img_base64)
        
        # 删除临时文件
        os.remove(screenshot_path)
        
        if result:
            print("网页图片发送成功！")
        else:
            print("网页图片发送失败。")
        
        return result
    
    except Exception as e:
        print(f"处理网页截图过程中出错: {e}")
        return False


# 示例使用方法
if __name__ == "__main__":
    # 示例1：截取整个页面
    asyncio.run(capture_and_send_webpage("https://www.wnlcha.com/", ".main-box1"))
 
    # 运行主函数（处理本地图片）
    # asyncio.run(main())